package game.tictactoe.pojo;

public class Board
{
	private Seed cells[][];
	private int rowIndex;
	private int columnIndex;

	public Board(int rowIndex, int columnIndex)
	{
		this.rowIndex = rowIndex;
		this.columnIndex = columnIndex;
		cells = new Seed[rowIndex][columnIndex];
		for (int i = 0; i < rowIndex; i++)
		{
			for (int j = 0; j < columnIndex; j++)
			{
				cells[i][j] = Seed.EMPTY;
			}
		}
	}

	public Seed getCellValue(int rowIndex, int colIndex)
	{
		return cells[rowIndex][colIndex];
	}
	/**
	 * This method is used to check if a move in the board is valid. Before returning the result, gameStatus is updated
	 * 
	 * @param i
	 *            Row index for the move in board
	 * @param j
	 *            Column index for the move in board
	 * @param value
	 *            Player value which is +1 for Player1, -1 for Player2
	 * @return True - if move is valid. False - if move is invalid
	 */
	public boolean isMoveValid(int i, int j, Seed value)
	{
		boolean isMoveValid = false;

		if (i > -1 && i < rowIndex && j > -1 && j < columnIndex)
		{
			Seed currentValue = cells[i][j];
			if (currentValue.compareTo(Seed.EMPTY) == 0)
			{
				isMoveValid = true;
				cells[i][j] = value;
			}
		}
		return isMoveValid;
	}
	
	public boolean isBoardFull()
	{
		for(int i=0; i< rowIndex; i++)
		{
			for(int j=0; j<columnIndex; j++)
			{
				if(cells[i][j].compareTo(Seed.EMPTY) == 0)
				{
					return false;
				}
			}
		}
		return true;
	}

	
	public String toStringForPatternMatching(Seed playerSeed)
	{
		StringBuilder sb = new StringBuilder();
		
		for (int i = 0; i < rowIndex; i++)
		{
			for (int j = 0; j < columnIndex; j++)
			{
				if(cells[i][j].compareTo(playerSeed) == 0)
					sb.append(playerSeed.toString());
				else
					sb.append("*");
			}
		}
		
		return sb.toString();
	}

	
	public boolean undoMove(int rowIndex, int colIndex, Seed seed)
	{
		if(cells[rowIndex][colIndex] != seed) 
			return false;
		cells[rowIndex][colIndex] = Seed.EMPTY;
		return true;
	}
	
	public String toString()
	{
		StringBuilder sb = new StringBuilder("Board:\n");

		for (int i = 0; i < rowIndex; i++)
		{
			for (int j = 0; j < columnIndex; j++)
			{
				sb.append(cells[i][j].toString());
				if (j != 2)
					sb.append("| ");
			}
			sb.append("\n");
		}
		return sb.toString();
	}

	public int getRowIndex()
	{
		return rowIndex;
	}

	public void setRowIndex(int rowIndex)
	{
		this.rowIndex = rowIndex;
	}

	public int getColumnIndex()
	{
		return columnIndex;
	}

	public void setColumnIndex(int columnIndex)
	{
		this.columnIndex = columnIndex;
	}
	
	
}
